/* eslint-disable camelcase */
<!-- Author: Edwin -->
<template>
  <div class="all">
    <div class="action">
      <div class="search-area">
        <div class="title">Blocks</div>
        <!-- <el-input size="mini"
                  placeholder="Search Block">
          <el-button slot="append"
                     icon="el-icon-search"></el-button>
        </el-input> -->
      </div>
      <div class="block-list">
        <el-tabs v-model="blockType">
          <el-tab-pane label="Triggers"
                       name="tab-trigger">
            <div class="card-content scroll-css">
              <BlockItem v-for="(item, i) in triggerBlocksList"
                         :key="i"
                         :blockInfo='item' />
            </div>
          </el-tab-pane>
          <el-tab-pane label="Actions"
                       name="tab-action">
            <div class="card-content scroll-css">
              <BlockItem v-for="(item, i) in actionBlocksList"
                         :key="i"
                         :blockInfo='item' />
            </div>
          </el-tab-pane>
          <el-tab-pane label="Loggers"
                       name="tab-logger">
            <div class="card-content scroll-css">
              <BlockItem v-for="(item, i) in loggerBlocksList"
                         :key="i"
                         :blockInfo='item' />
            </div>
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>
    <div class="content">
      <div class="header">
        <div class="header-name">{{ botInfo.name }}</div>
        <el-button-group>
          <el-button @click="deleteAllBlocks"
                     size="mini"
                     type="primary">Clear</el-button>
          <el-button @click="confirmFlowy"
                     size="mini"
                     type="success">Save</el-button>
          <el-button @click="importFlowy"
                     size="mini"
                     type="info">Reset</el-button>
        </el-button-group>
      </div>
      <div ref="canvas"
           id="canvas"
           class="scroll-css canvas"></div>
    </div>
  </div>
</template>

<script>
import flowy from 'flowy'
import BlockItem from './components/block-item'

export default {
  props: {
    botId: {
      type: String,
      default: ''
    }
  },
  components: { BlockItem },
  data () {
    return {
      blockType: 'tab-trigger',
      blocksList: [],
      botInfo: {}
    }
  },
  computed: {
    triggerBlocksList () {
      return this.blocksList.filter(e => e.type === 'trigger')
    },
    actionBlocksList () {
      return this.blocksList.filter(e => e.type === 'action')
    },
    loggerBlocksList () {
      return this.blocksList.filter(e => e.type === 'logger')
    }
  },
  mounted () {
    /* eslint-disable */
    const spacing_x = 40
    const spacing_y = 100
    // Initialize Flowy
    flowy(this.$refs['canvas'], onGrab, onRelease, onSnap, onRearrange, spacing_x, spacing_y)
    function onGrab (block) {
      // When the user grabs a block
    }
    function onRelease () {
      // When the user releases a block
    }
    function onSnap (block, first, parent) {
      // When a block snaps with another one
      return true
    }
    function onRearrange (block, parent) {
      // When a block is rearranged
      return false
    }
  },
  created () {
    if (this.botId) {
      this.getBlocksList()
      this.getBotInfo()
    }
  },
  methods: {
    getBlocksList () {
      this.$interface.bots.getTenantScriptListApi({ tenantId: this.$store.state.user.tenantCode })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.blocksList = res.data
        }).catch(() => { })
    },
    getBotInfo () {
      this.$interface.botStore.getTenantBotInfoApi({ id: this.botId })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.botInfo = res.data
          this.importFlowy() // reset page
        })
        .catch(() => { })
    },
    updateBotInfo (params) {
      this.$interface.botStore.putBotUpdateScriptApi(this.botId, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
        })
        .catch(() => { })
    },
    getSysBotScriptList (flowSetting) {
      let tempList = []
      if (flowSetting) {
        let blocks = flowSetting.blocks
        for (let i = 0; i < blocks.length; i++) {
          const item = blocks[i]
          const blockInfo = getBlockInfo(item.attr)
          tempList.push({
            botId: this.botId,
            scriptId: blockInfo.id,
            triggerId: item.parent < 0 ? this.botId : getTriggerId(item.parent),
            paramsValue: blockInfo.paramsValue
          })
        }
        function getTriggerId (parentId) {
          try {
            return getBlockInfo(blocks.find(e => e.id === parentId).attr).id
          } catch (error) {
            return null
          }
        }
        function getBlockInfo (attr) {
          try {
            return JSON.parse(attr.find(e => Boolean(e.blockinfo) === true).blockinfo)
          } catch (error) {
            return null
          }
        }
      }
      return tempList
    },
    deleteAllBlocks () {
      flowy.deleteBlocks()
    },
    confirmFlowy () {
      if (!this.botId) { return false }
      const params = {
        ...this.botInfo,
        flowSetting: flowy.output(),
        sysBotScriptList: this.getSysBotScriptList(flowy.output())
      }
      this.updateBotInfo(params)
    },
    importFlowy () {
      let temp = this.botInfo.flowSetting
      if (temp) {
        flowy.deleteBlocks()
        flowy.import(temp)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
@import "./index.scss";
</style>
